package com.hs.srm.admin.modules.harmfulsubstance.controller;

import com.hs.srm.admin.modules.harmfulsubstance.entity.ReportRepositoryEntity;
import com.hs.srm.admin.modules.harmfulsubstance.service.ReportRepositoryService;
import com.hs.srm.admin.modules.sys.controller.AbstractController;
import com.hs.srm.admin.modules.vendor.entity.VendorInfoEntity;
import com.hs.srm.admin.modules.vendor.service.VendorService;
import com.hs.srm.base.common.annotation.SysLog;
import com.hs.srm.base.modules.sys.entity.SysUserEntity;
import com.hs.srm.common.utils.PageUtils;
import com.hs.srm.common.utils.R;
import com.hs.srm.tools.FileUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * (ReportRepositoryEntity)表控制层
 *
 * @author ych
 * @since 2020-03-17 16:42:42
 */
@RestController
@RequestMapping("/reportRepository")
public class ReportRepositoryController extends AbstractController {

    @Autowired
    private ReportRepositoryService reportService;

    @Autowired
    private VendorService vendorService;

    @Value("${hssrm.file-upload-path}")
    protected String fileUploadPath;

    /**
     * 查询列表
     *
     * @param params
     * @return
     */
    @RequestMapping("/list")
    public R list(@RequestParam Map<String, Object> params) {
        SysUserEntity username = this.getUser();
        if (username.getDeptId() == 13) {
            params.put("username", username.getUsername());
        }
        PageUtils page = reportService.queryPage(params);
        return R.ok(page);
    }

    /**
     * 查询该测试报告存不存在
     *
     * @param reportCode,测试报告编号，多个以英文逗号,隔开
     * @return
     */
    @RequiresPermissions("report:add")
    @GetMapping("/checkReportCode")
    public R checkReportCode(String reportCode) {
        String[] codes = reportCode.split(",");
        List<ReportRepositoryEntity> list = reportService.selectBatchCodes(codes, this.getUser().getUsername());

        //查询结果和前端传来的数量一致，报告存在
        if (CollectionUtils.isNotEmpty(list) && codes.length == list.size()) {
            return R.ok(list.size());
        }

        //查询数据量不等于前端传过来的报告编号数量，有报告不存在，返回不存在的报告编号
        R r = new R();
        r.put("result", 0);
        List co = Stream.of(codes).collect(Collectors.toList());
        //将前端传来的编码去掉查询结果中的编码，剩下的就是没有不存在的
        System.out.println(list.stream().map(ReportRepositoryEntity::getReportCode).collect(Collectors.toList()));
        co.removeAll(list.stream().map(ReportRepositoryEntity::getReportCode).collect(Collectors.toList()));
        r.put("reportCode", co.toString());
        return r;
    }

    @SysLog("供应商新增报告")
    @RequiresPermissions("report:add")
    @PostMapping("/saveReport")
    public R saveReport(ReportRepositoryEntity entity, HttpServletRequest request) throws IOException, ServletException {
        VendorInfoEntity vendor = vendorService.selectByVendorCode(this.getUser().getUsername());
        return reportService.saveReport(entity, request, vendor.getSapCode(), vendor.getVendorName());
    }

    /**
     * 根据id下载附件
     */
    @RequestMapping("/downloadFileById")
    public void downloadFileById(String id, HttpServletRequest request, HttpServletResponse response) throws IOException {
        ReportRepositoryEntity re = reportService.selectById(id);
        File file = new File(this.fileUploadPath + re.getAttach());
        FileUtils.fileDownload(file, request, response);
    }

    /**
     * 返回报告更新页面
     *
     * @param pkId
     * @return
     */
    @RequiresPermissions("report:update")
    @GetMapping("/updateReport/{pkId}")
    public ModelAndView updateReport(@PathVariable("pkId") String pkId) {
        ReportRepositoryEntity entity = reportService.selectById(pkId);
        ModelAndView modelAndView = new ModelAndView("modules/harmful/rohs/report_update");
        //将附件前的路径去掉及上传文件时添加的时间，返回文件名。例：/aaa/bb/asd_20201010121212.txt --> asd.txt
        entity.setAttach(entity.getAttach().substring(entity.getAttach().lastIndexOf("/") + 1));
        entity.setAttach(entity.getAttach().replaceAll("_\\d+", ""));
        modelAndView.addObject("report", entity);
        return modelAndView;
    }

    /**
     * 根据id废弃报告
     *
     * @param pkId
     * @return
     */
    @SysLog("供应商作废报告")
    @RequiresPermissions("report:nullify")
    @GetMapping("/nullifyReport")
    public R nullifyReport(String pkId) {
        ReportRepositoryEntity entity = new ReportRepositoryEntity();
        entity.setPkId(pkId);
        entity.setValid(-1);
        reportService.updateById(entity);
        return R.ok();
    }

    /**
     * 获取即将过期的供应商报告数量
     *
     * @return
     */
    @GetMapping("/reportNotice")
    public R reportNotice() {
        String vendorCode = this.getUser().getUsername();
        Map<String, Integer> map = reportService.getWarningCount(vendorCode);
        return R.ok(map);
    }

    /**
     * 根据供应商编码，测试报告编号获取报告库中数据
     *
     * @param vendorCode
     * @param reportCode
     * @return
     */
    @GetMapping("/reportDataByCode")
    public R reportDataByCode(String vendorCode, String reportCode) {
        ReportRepositoryEntity entity = reportService.reportDataByCode(vendorCode, reportCode);
        //将附件前的路径去掉及上传文件时添加的时间，返回文件名。例：/aaa/bb/asd_20201010121212.txt --> asd.txt
        entity.setAttach(entity.getAttach().substring(entity.getAttach().lastIndexOf("/") + 1));
        entity.setAttach(entity.getAttach().replaceAll("_\\d+", ""));

        return R.ok(entity);
    }

}